<?php  
	if(!defined('DB_FILE')){
		$url="../../Index.php";
		include_once '../Common/Redirect.php';
		exit();
	}	
	class SqlDBManager{
		private $dbh = NULL;
		
		public function __construct(){
			try{
				$this->dbh= new PDO("mysql:host=".DB_HOST.";port=".DB_PORT.";dbname=".DB_DATABASE_NAME,DB_USERNAME,DB_PASSWORD);
				$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			}catch (PDOException $e){
				$this->logger($e->getMessage());
				die(("HTTP Error 503 Service Unavailable. The database is currently down for system maintenance."));	
			}
		}

		//Query rows
		public function queryRows($sql, $parameters = null) {  
			$res = $this->execute_dql($sql, $parameters);
			return $res; 
    	}
    	
    	//Query one row
    	public function queryRow($sql, $parameters = null) {
    		$res = $this->execute_dql($sql, $parameters);
    		if (count($res) > 0) {
    			return $res[0];
    		} else {
    			return null;
    		}
    	}
    	
    	//Execute DQL statements
    	public function execute_dql($sql, $parameters = null) {
    		try{
    			$pdoStmt = $this->dbh->prepare($sql);
    			$pdoStmt->execute($parameters);
    			$res = $pdoStmt->fetchAll();
    			$pdoStmt = null;
    			return $res;
    		}catch(PDOException $e){
    			$this->logger($e->getMessage());
    			return false;
    		}
    	}
		
		//Execute DML statements
		public function execute_dml($sql,$parameters=null){
			try{
				$pdoStmt = $this->dbh->prepare($sql);
				$pdoStmt->execute($parameters);
				$affectedRows = $pdoStmt->rowCount();
        		$pdoStmt = null;
        		return $affectedRows;
			}catch(PDOException $e){
				$this->logger($e->getMessage());
    			return false;
			}
		}
		
		//Close connection
		public  function close_connect(){
			if(!empty($this->dbh)){
				$this->dbh=null;
			}
		}
		
		private function logger($msg='') {
			file_put_contents(DATABASE_LOG_PATH,'[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL,FILE_APPEND);
		}		
	}
?>